local skynet = require "skynet"
require "skynet.manager"
local mysql = require "skynet.db.mysql"
local log = require "sky_log"

local M = {
    mysql_connect_t = nil,
}

function M:connect(config)
    if not self.mysql_connect_t then
        self.mysql_connect_t = {}
    end

    if not tonumber(config.plat_id) then
        log.error("mysql connect error: no plat_id!")
        return
    end

    local index = config.plat_id
    self.mysql_connect_t[index] = {}
    local conf = {}
    conf.host = config.mysql_host
    conf.port =  config.mysql_port
    conf.user =  config.mysql_user
    conf.password = config.mysql_password
    conf.database = config.mysql_db
    conf.charset =  'utf8'
    --conf.db_timeout = config.db_timeout

    local mysql_index = mysql.connect(conf)
    if mysql_index then 
        mysql_index:query("set charset ".. conf.charset)
        self.mysql_connect_t[index].conf = conf
        self.mysql_connect_t[index].mysql_index = mysql_index
        log.warning("connect plat_id: ["..index.."] mysql success!")
    end
end

function M:call_sql(plat_id, sql)
    if not plat_id 
    or not sql 
    or not self.mysql_connect_t[plat_id] then 
        log.error("call_sql error! | plat_id:"..(plat_id or "nil")
            .." | sql:"..(sql or "nil"))
        return
    end

    local mysql_index = self.mysql_connect_t[plat_id].mysql_index
    local res = mysql_index:query(sql)

    if res[1] then 
        return res
    else
        return res.err 
    end
end

function  M:init_by_config(data)
    self:connect(data)
end

skynet.start(function ()
    skynet.dispatch("lua", function(session, address, cmd, ...)
        --log.info("M dispatch session=", session)
        --log.info("M dispatch address=", address)
        --log.info("M dispatch cmd=", cmd)
        local f = M[cmd]
        if f then
            skynet.ret(skynet.pack(f(M, ...)))
        else
            skynet.error(string.format("Unknown command %s", tostring(cmd)))
        end
    end)

    skynet.register(".mysql")
end)

return M